package org.me.dubbodemo.appbase.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.me.dubbodemo.appbase.Util.TraceUtil;
import org.me.dubbodemo.appbase.constants.TraceConst;
import org.slf4j.MDC;

@Activate(group = CommonConstants.PROVIDER, order = 1)
public class DubboProviderTraceFilter implements Filter {
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        final String trace = TraceUtil.getOrInitTraceFromRpcContext();
        TraceUtil.populateTraceToMDC(trace);
        invocation.setAttachment(TraceConst.TRACE_KEY, trace);
        Result result;
        try {
            result = invoker.invoke(invocation);
        } finally {
            MDC.clear();
        }
        return result;
    }
}